# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from cemberus.html_meta.models import DateMeta, HtmlMeta, StatCloneableMixin
from cemberus.categories.models import Category


class BlogRoll(DateMeta, models.Model):
    user = models.ForeignKey(User, verbose_name = _('Benutzername'))
    category = models.ForeignKey(Category, verbose_name = _('Kategorie'))
    
    name = models.CharField(verbose_name = _('Name'), max_length = 80)
    url = models.URLField(verbose_name = _('URL'), verify_exists = False)
    description = models.TextField(verbose_name = _('Beschreibung'))
    
    def __unicode__(self):
        return self.name
        
    class Meta:
        verbose_name = _(u'Blogroll')
        verbose_name_plural = _('Blogroll')
        
        
class Post(DateMeta, models.Model):
    user = models.ForeignKey(User, verbose_name = _('Benutzername'))
    
    slug = models.SlugField(verbose_name = ('URL'), max_length = 180, unique = True)
    
    def get_live_revision(self):
        return self.revisions.get(status__gte = PostRevision.STATUS_PUBLIC)
        
    def get_latest_revision(self):
        try:
            return self.revisions.all().order_by('-created')[0]
        except IndexError:
            raise PostRevision.DoesNotExist()
            
    def add_revision(self, base = None):
        if base is None:
            try:
                base = self.get_live_revision()
            except PostRevision.DoesNotExist:
                try:
                    base = self.get_latest_revision()
                except PostRevision.DoesNotExist:
                    return PostRevision.objects.create(post = self)
        return base.clone()
        
    def publish_revision(self, revision):
        self.revisions.exclude(pk = revision.pk).filter(status = PostEntry.STATUS_PUBLIC).update(status = PostRevision.STATUS_ARCHIVE)
        self.revisions.filter(pk = revision.pk).update(status = PostRevision.STATUS_PUBLIC)
        revision.status = PostRevision.STATUS_PUBLIC
        return revision
    
    def __unicode__(self):
        return self.slug
    
    class Meta:
        verbose_name = _(u'Eintrag')
        verbose_name = _(u'Einträge')
        
        
class PostRevisionCloneableMixin(StatCloneableMixin):
    def _clone_prepare(self, duplicate):
        super(PostRevisionCloneableMixin, self)._clone_prepare(duplicate)
        duplicate.status = self.STATUS_DRAFT
        
        
class PostRevision(HtmlMeta, DateMeta, PostRevisionCloneableMixin, models.Model):
    post = models.ForeignKey(Post, related_name = 'revisions', verbose_name = _('Eintrag'))
    category = models.ForeignKey(Category, verbose_name = _('Kategorie'))
    
    STATUS_DRAFT = 10
    STATUS_PUBLIC = 20
    STATUS_PRIVATE = 30
    STATUS_ARCHIVE = 40
    
    STATUS_CHOICES = (
        (STATUS_DRAFT, _(u'Draft')),
        (STATUS_PUBLIC, _(u'Öffentlich')),
        (STATUS_PRIVATE, _(u'Privat')),
        (STATUS_ARCHIVE, _(u'Archiv')),
    )
    
    # required fields
    title = models.CharField(verbose_name = _('Titel'), max_length = 180)
    summary = models.TextField(verbose_name = _('Zusammenfassung'))
    text = models.TextField(verbose_name = _('Text'))
    image = models.ImageField(verbose_name = _('Artikelbild'), upload_to = 'blog/images')
    status = models.CharField(verbose_name = _('Artikelstatus'), max_length = 2, choices = STATUS_CHOICES, default = STATUS_DRAFT)
    
    def has_previous_revision(self):
        try:
            self.get_previous_revision()
            return True
        except PostRevision.DoesNotExist:
            return False
            
    def has_next_revision(self):
        try:
            self.get_next_revision()
        except PostRevision.DoesNotExist:
            return False
            
    def get_previous_revision(self):
        try:
            return PostRevision.objects.filter(post = self.post, created__lt = self.created).order_by('-created')[0]
        except IndexError:
            raise PostRevision.DoesNotExist()
            
    def get_next_revision(self):
        try:
            return PostRevision.objects.filter(post = self.post, created__gt = self.created).order_by('created')[0]
        except IndexError:
            raise PostRevision.DoesNotExist()
    
    def __unicode__(self):
        return self.title + ' - ' + str(self.status)
        
    class Meta:
        verbose_name = (u'Eintragsrevision')
        verbose_name = (u'Eintragsrevisionen')
        
